import { useRef } from 'react'
import SessionList from '@/components/Slider/SessionList'
import clsx from 'clsx'
import { useAtom } from 'jotai'
import { styled } from '@mui/material/styles'
import { useTranslation } from 'react-i18next'
import { Box, IconButton, Tooltip } from '@mui/material'
import { drawSlideShow } from '@/atoms'
import useChat from '@/hooks/useChat'
import { showAlertDialog } from '@/components/Base/Alert'

const DrawSlide = styled(Box)(({ theme }) => ({
  transition: theme.transitions.create(['width'], {
    duration: theme.transitions.duration.standard,
  }),
}),
)

export default function Sidebar() {
  const { t } = useTranslation()
  const [drawStatus, setDrawShow] = useAtom(drawSlideShow)
  const sessionListRef = useRef<HTMLDivElement>(null)
  const { newChat, clearChats } = useChat()

  const handleCreateNewSession = () => {
    newChat()
    if (sessionListRef.current) {
      sessionListRef.current.scrollTo(0, 0)
    }
  }
  const handleClearSession = () => {
    showAlertDialog({
      title: t('make sure for delete'),
      content: t('cant reply if delete'),
      onOk: () => {
        clearChats()
      },
    })
  }

  return (
    <DrawSlide className={clsx('h-full bg-gray-50 shadow overflow-hidden gap-2 flex flex-col dark:bg-[#171717]', {
      'w-22rem': drawStatus,
      'w-0': !drawStatus,
    })}
    >
      <Box className="h-3.5rem w-full flex items-center justify-between px-1rem shadow-custom-light">
        <h3 className="font-jersey text-2rem">Moss</h3>
        <IconButton size="small" onClick={() => setDrawShow(!drawStatus)} color="inherit">
          <Box className="i-material-symbols:format-indent-decrease-rounded" />
        </IconButton>
      </Box>
      <div className="h-full flex flex-col">
        <div className="flex justify-start px-0.4rem">
          <Tooltip title={t('newChat tip')} arrow>
            <IconButton color="primary" size="small" onClick={handleCreateNewSession}>
              <div className="i-material-symbols:chat-add-on-sharp" />
            </IconButton>
          </Tooltip>
          <Tooltip title={t('clearChats tip')} arrow>
            <IconButton color="primary" size="small" onClick={handleClearSession}>
              <div className="i-material-symbols:layers-clear" />
            </IconButton>
          </Tooltip>
        </div>
        <SessionList />
      </div>
    </DrawSlide>
  )
}
